package com.xyzh05.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.service.EditorManager;
import com.xyzh05.model.Editor;
import com.xyzh05.webapp.action.BaseAction;

import java.util.List;

public class EditorAction extends BaseAction implements Preparable {
    private EditorManager editorManager;
    private List editors;
    private Editor editor;
    private Long id;
    private String query;

    public void setEditorManager(EditorManager editorManager) {
        this.editorManager = editorManager;
    }

    public List getEditors() {
        return editors;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String editorId = getRequest().getParameter("editor.id");
            if (editorId != null && !editorId.equals("")) {
                editor = editorManager.get(new Long(editorId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        editors = editorManager.search(query, Editor.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Editor getEditor() {
        return editor;
    }

    public void setEditor(Editor editor) {
        this.editor = editor;
    }

    public String delete() {
        editorManager.remove(editor.getId());
        saveMessage(getText("editor.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            editor = editorManager.get(id);
        } else {
            editor = new Editor();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (editor.getId() == null);

        editorManager.save(editor);

        String key = (isNew) ? "editor.added" : "editor.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}